package clock

import (
	"data/config"
	"data/view/auth"
	"data/view/auth/auth_const"
	"data/view/common"
	"data/view/interview"
	"data/view/oplog"
	"data/view/school"
	"data/view/user"
	"public/message"
	"public/mysqldb"
	"public/tools"
	"strconv"
	"time"

	"github.com/ant0ine/go-json-rest/rest"
)

//获取打卡范围
func GetRange(w rest.ResponseWriter, r *rest.Request) {
	var req GetRangeParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) || req.Lat == 0 || req.Lon == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_12, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//判断是否正确人员
	var interview interview.Interview_sheet_tbl
	orm.Where("person = ? and person_type = ? and start_time <= ? and end_time >= ?", username, 1, time.Now(), time.Now()).
		Find(&interview)

	if interview.Id > 0 {
		var schools, result []school.School_info_tbl
		orm.Find(&schools)
		if len(schools) > 0 {
			for _, v := range schools {
				if CheckRegionRange(interview.Province, interview.City, interview.Region, v.Province, v.City, v.Region) {
					if common.EarthDistance(req.Lat, req.Lon, v.Lat, v.Lon) <= v.Clock_range { //在打卡范围内
						result = append(result, v)
					}
				}
			}
		}
		msg := message.GetSuccessMsg(message.NormalMessageId)
		msg.Data = result
		w.WriteJson(msg)
	} else {
		w.WriteJson(message.GetErrorMsg(message.InValidOp))
		return
	}

}

//打卡
func Action(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.School_name, req.Province, req.City, req.Region) || req.Lat == 0 || req.Lon == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_12, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//判断是否正确人员
	var interview interview.Interview_sheet_tbl
	orm.Where("person = ? and person_type = ? and start_time <= ? and end_time >= ?", username, 1, time.Now(), time.Now()).
		Find(&interview)

	if interview.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.InValidOp))
		return
	}
	var school school.School_info_tbl
	orm.Where("name = ? and province = ? and city = ? and region = ?", req.School_name, req.Province, req.City, req.Region).Find(&school)
	if school.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError))
		return
	}
	if !CheckRegionRange(interview.Province, interview.City, interview.Region, req.Province, req.City, req.Region) {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "不在打卡范围"))
		return
	}

	if common.EarthDistance(req.Lat, req.Lon, school.Lat, school.Lon) > school.Clock_range { //不在打卡范围内
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "不在打卡范围"))
		return
	}
	var err error
	var record Clock_record_tbl
	clock_time := time.Now()
	record.Attach = req.Attach
	record.Clock_time = clock_time
	record.Lat = req.Lat
	record.Lon = req.Lon
	record.School_id = school.Id
	record.User = username
	record.Clock_date = time.Now().Format("2006-01-02")

	if req.Clock_time.Time.IsZero() { //新增打卡
		var tmp []Clock_record_tbl
		orm.Where("user = ? and clock_date = ?", username, time.Now().Format("2006-01-02")).Find(&tmp)
		if len(tmp) >= 2 {
			w.WriteJson(message.GetErrorMsg(message.InValidOp, "每日至多2次打卡"))
			return
		}
		err = orm.Create(&record).Error
	} else { //更新打卡
		err = orm.Table("clock_record_tbl").Where("clock_time = ?", req.Clock_time.Time).Updates(record).Error
	}
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	//保存日志
	var logs oplog.Op_log_tbl
	logs.Operator = username
	logs.Topic = "面试"
	logs.Bundle = "出差面试"
	logs.Pid = "考勤打卡"
	logs.Ip_addr = tools.GetClientIp(r.Request)
	logs.Tm0 = clock_time
	logs.Attach0 = strconv.FormatFloat(req.Lat, 'E', -1, 64) //纬度
	logs.Attach1 = strconv.FormatFloat(req.Lon, 'E', -1, 64) //经度
	oplog.OpLogBaseAdd(logs)
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = clock_time
	w.WriteJson(msg)
}

//获取自己当天的打卡记录
func GetMine(w rest.ResponseWriter, r *rest.Request) {
	var req GetRangeParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_12, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var result []Clock_record_info

	orm.Table("clock_record_tbl as c ").Select("c.*,s.name,s.province,s.city,s.region").Joins("join school_info_tbl as s on c.school_id = s.id").
		Where("c.user = ? and c.clock_date = ?", username, time.Now().Format("2006-01-02")).Find(&result)
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = result
	w.WriteJson(msg)
}
